package com.manager.core.module.manager.service;

import java.util.List;
import java.util.Map;

import com.manager.commons.utils.StringUtil;
import com.manager.core.module.manager.entity.ThreePermissionList;
import com.manager.commons.mybatis.service.GenericService;
import com.manager.core.shiro.realm.SecurityRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.manager.commons.utils.DateUtil;
import com.manager.commons.mybatis.dao.GenericDao;
import com.manager.core.module.manager.dao.PlatformRolePermissionDao;
import com.manager.core.module.manager.entity.PlatformRolePermission;
import com.manager.gen.module.platform.core.entity.view.PlatformRolePermissionView;
import com.manager.core.web.json.AjaxJson;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * PlatformRolePermissionService
 *
 * @author H
 * @version 1.0
 */
@Service
public class PlatformRolePermissionService extends GenericService<PlatformRolePermission> {

    @Autowired
    private PlatformRolePermissionDao jdbcDao;
    @Autowired
    SecurityRealm securityRealm;

    @Override
    public GenericDao<PlatformRolePermission> getDao() {
        return jdbcDao;
    }

    /**
     * @param map
     * @return
     */
    public JSONArray queryRolePermissionTree(Map<String, Object> map) {
        JSONArray jres = null;
        List<PlatformRolePermissionView> vres = jdbcDao.queryTree(map);
        if (null != vres && vres.size() > 0) {
            jres = getTreePermission(vres, "top");
        }
        return jres;
    }

    /**
     * 获取Tree Permission
     *
     * @param spvs
     * @param pid
     * @return
     */
    protected JSONArray getTreePermission(List<PlatformRolePermissionView> spvs, String pid) {
        JSONArray trees = new JSONArray();
        for (PlatformRolePermissionView spv : spvs) {
            if (pid.equals(spv.getPpParent())) {
                JSONObject tree = new JSONObject();
                tree.put("id", spv.getPpCode());
                tree.put("text", spv.getPpName());
                tree.put("type", spv.getPpType());
                tree.put("auth", spv.getPpAuth());
                tree.put("checked", (spv.getPpNum() > 0));
                tree.put("expanded", false);
                tree.put("children", getTreePermission(spvs, spv.getPpCode()));
                trees.add(tree);
            }
        }
        return trees;
    }

    /**
     * 保存
     *
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson save(Map<String, Object> _map) {
        try {
            if (null != _map) {
                if (_map.containsKey("_ids")) {
                    String _id = _map.get("_ids") + "";
                    String[] _ids = _id.split(",");
                    _map.put("_ids", _ids);
                }
                _map.put("createTime", DateUtil.currentDateTime());
                // 先删除已有权限值
                int f = jdbcDao.destroyMap(_map);
                if (f >= 0) {
                    f = jdbcDao.insertMap(_map);
                    return new AjaxJson(f);
                }
                return new AjaxJson(f);
            }
            return new AjaxJson("参数错误");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new AjaxJson("异常错误，请稍后再试");
    }

    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson savePermission(Map<String, Object> _map) throws Exception {
        try {
            String ids = getParamsString(_map, "_ids");
            // 先删除已有权限值
            jdbcDao.deleteRolePermission(_map);
            if (StringUtil.isNotEmpty(ids)) {
                jdbcDao.insertMap(_map);
            }
            securityRealm.updateAuthorization();
            return new AjaxJson(1);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 查询权限树
     *
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public List<ThreePermissionList> queryPermissionnaxTree(Map<String, Object> _map) {
        List<ThreePermissionList> lhldLists = jdbcDao.queryPermissionnaxTree(_map);
        if (lhldLists != null && !lhldLists.isEmpty()) {
            queryPermissionnaxTree(_map, lhldLists);
        }
        if (lhldLists != null) {
            for (ThreePermissionList top : lhldLists) {
                if (top.getChildren() != null) {
                    for (ThreePermissionList child : top.getChildren()) {
                        if (child.getChildren() != null) {
                            for (ThreePermissionList child2 : child.getChildren()) {
                                child2.setChecked(child2.getMenuCheck() >= 1);
                            }
                        } else {
                            child.setChecked(child.getMenuCheck() >= 1);
                        }
                    }
                } else {
                    top.setChecked(top.getMenuCheck() >= 1);
                }

            }
        }


        return lhldLists;
    }

    /**
     * 递归循环加载菜单
     *
     * @param _map
     * @param lhldLists
     */
    public void queryPermissionnaxTree(Map<String, Object> _map, List<ThreePermissionList> lhldLists) {
        for (ThreePermissionList child : lhldLists) {
            if (child.getChildCount() > 0) {
                _map.put("code", child.getId());
                List<ThreePermissionList> childList = jdbcDao.queryPermissionnaxTree(_map);
                child.setChildren(childList);
                queryPermissionnaxTree(_map, childList);
            }
        }
    }

    @Override
    public PlatformRolePermission getModel() {
        return new PlatformRolePermission();
    }
}